package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mgr/cache"
	"novel-mgr/models"
	"novel-mgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"data": "字段不能为空",
		})
		return
	}
	redis_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	//
	var novel models.Novel
	redis_key := "list_page" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	//
	if result == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(result), &novel)
	}
	//
	var total int64
	models.DB.Model(&models.Novel{}).Count(&total)
	//
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  novel,
		"total": total,
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var novel models.Novel
	models.DB.Where("id=?", id).First(&novel)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": novel,
	})
	return
}
